package com.fmsz.physicalheadline.fragments.head;


import android.databinding.DataBindingUtil;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.util.Pair;
import android.support.v4.view.ViewCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.fmsz.physicalheadline.BR;
import com.fmsz.physicalheadline.R;
import com.fmsz.physicalheadline.adapter.news.RecycleAdapter;
import com.fmsz.physicalheadline.application.MyApplication;
import com.fmsz.physicalheadline.databinding.FragmentHeadBinding;
import com.fmsz.physicalheadline.databinding.MatchTimeBinding;
import com.fmsz.physicalheadline.entity.top.HeadEntity;
import com.fmsz.physicalheadline.interfaces.HttpService;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * A simple {@link Fragment} subclass.
 */
public class HeadFragment extends Fragment implements Callback<HeadEntity>, SwipeRefreshLayout.OnRefreshListener {


    private FragmentHeadBinding binding;
    private RecycleAdapter<Object> adapter;
    private HttpService service;
    private MatchTimeBinding timeBinding;
    private boolean isRefresh;

    public HeadFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = DataBindingUtil.inflate(LayoutInflater.from(getContext()), R.layout.fragment_head, container, false).getRoot();
        binding = DataBindingUtil.bind(view);
        timeBinding = DataBindingUtil.inflate(LayoutInflater.from(getContext()), R.layout.match_time, binding.frameLayout, false);
        binding.frameLayout.addView(timeBinding.getRoot());
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {

        service = ((MyApplication) getContext().getApplicationContext()).getHttpService();
        service.getTopHeadData().enqueue(this);
        Map<Class<?>, Pair<Integer, Integer>> map = new HashMap<>();
        map.put(HeadEntity.Data.Heads.class, Pair.create(R.layout.top_head_item, BR.heads));
        map.put(Date.class, Pair.create(R.layout.match_time, BR.start));
        adapter = new RecycleAdapter<>(getContext(), new ArrayList<>(), map);
        binding.recycleHead.setAdapter(adapter);
        RecyclerView.ItemDecoration decoration = new RecyclerView.ItemDecoration() {
            @Override
            public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
                super.onDraw(c, parent, state);
            }

            @Override
            public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
                super.onDrawOver(c, parent, state);
            }

            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.set(0, 0, 0, 3);
            }
        };
        binding.recycleHead.addItemDecoration(decoration);
        binding.swipe.setOnRefreshListener(this);
        binding.recycleHead.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                View childAt = recyclerView.getChildAt(0);
                int position = recyclerView.getChildAdapterPosition(childAt);
                for (int j = position; j >= 0; j--) {
                    Object item = adapter.getItem(j);
                    if (item instanceof Date) {
                        timeBinding.setStart((Date) item);
                        break;
                    }
                }
                for (int j = 1; j < recyclerView.getChildCount(); j++) {
                    View view1 = recyclerView.getChildAt(j);
                    int position1 = recyclerView.getChildAdapterPosition(view1);
                    if (view1.getTop() > timeBinding.getRoot().getHeight()) {
                        ViewCompat.setTranslationY(timeBinding.getRoot(), 0);
                        break;
                    }
                    if (adapter.getItemViewType(position1) == R.layout.match_time) {
                        ViewCompat.setTranslationY(timeBinding.getRoot(), view1.getTop() - timeBinding.getRoot().getHeight());
                        break;
                    }
                }
            }
        });

    }

    @Override
    public void onResponse(Call<HeadEntity> call, Response<HeadEntity> response) {

        if (isRefresh) {
            adapter.removeAll();
        }

        for (int i = 0; i < response.body().getData().getHeads().size(); i++) {
            if (i==0) {
                adapter.add(response.body().getData().getHeads().get(0).getCreate_time());
            }
            adapter.add(response.body().getData().getHeads().get(i));
            if (i < response.body().getData().getHeads().size() - 1) {
                SimpleDateFormat SDF = new SimpleDateFormat("yyyyMMdd", Locale.getDefault());
                Date time2 = response.body().getData().getHeads().get(i).getCreate_time();
                Date time1 = response.body().getData().getHeads().get(i + 1).getCreate_time();
                String s1 = SDF.format(time1);
                String s2 = SDF.format(time2);
                if (!s2.equals(s1)) {
                    adapter.add(response.body().getData().getHeads().get(i+1).getCreate_time());
                }
            }

            isRefresh = false;
            binding.swipe.setRefreshing(false);
        }
    }

    @Override
    public void onFailure(Call<HeadEntity> call, Throwable t) {
        t.printStackTrace();
        Log.i("1620", t.getMessage());
    }

    @Override
    public void onRefresh() {
        isRefresh = true;
        service.getTopHeadData().enqueue(this);
    }
}
